package com.lagou.handler;

import com.lagou.entity.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

/**
 *  自定义事件处理器
 */
public class UserClientHandler extends ChannelInboundHandlerAdapter implements Callable {

    private RpcRequest request;
    private ChannelHandlerContext context;
    private Object result; // 记录服务器返回的数据

    //1.连接成功时（初始化），获取ChannelHandlerContext
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.context=ctx;
    }

    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) {
        result = msg;
        notify();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

    public void setParam(RpcRequest request) {
        this.request = request;
    }
    //2.将客户端的请求写到服务器，然后线程挂起，直到异步读取到写入，再被唤醒并返回结果
    public synchronized Object call() throws Exception {
        context.writeAndFlush(request);
        //挂起，等待异步唤醒
        wait();
        return result;
    }
}
